package com.yhh.studysys.utils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**  
 * <p>Description: </p>  
 * @author yhh  
 * @date 2020年10月28日  
 */
public class CommonUtils {

    /**
     * 将一个List均分成n个list,主要通过偏移量来实现的
     *
     * @param source 源集合
     * @param limit 最大值
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int limit) {
        if (null == source || source.isEmpty()) {
            return Collections.emptyList();
        }
        List<List<T>> result = new ArrayList<>();
        int listCount = (source.size() - 1) / limit + 1;
        int remaider = source.size() % listCount; // (先计算出余数)
        int number = source.size() / listCount; // 然后是商
        int offset = 0;// 偏移量
        for (int i = 0; i < listCount; i++) {
            List<T> value;
            if (remaider > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remaider--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }
    
    /**
     * 
     * @param <T>
     * @param input 输入数据
     * @param exsit 已知数据
     * @return
     *      {"add":[],"remove":[]}
     *      add为需要添加的数据,remove为需要删除的数据
     */
    public static <T> Map<String,List<T>> addRemoveList(List<T> input , List<T> exsit){

        /*
         * 比较出入数据和数据库数据,找出需要添加/需要删除的关系
         */
        List<T> removeList = exsit.stream().filter(k -> !input.contains(k)).collect(Collectors.toList());
        
        List<T> addList = input.stream().filter(k -> !exsit.contains(k)).collect(Collectors.toList());
        
        Map<String,List<T>> map = new HashMap<>();
        map.put("add", addList);
        map.put("remove", removeList);
        
        return map;
        
    }
    
    /** 驼峰转下划线 */
    public static String humpToLine(String str) {
        Matcher matcher = Pattern.compile("[A-Z]").matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /** 下划线转驼峰 */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = Pattern.compile("_(\\w)").matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
